<template>
  <div>
    <div class="item-color-box">
      选择预包装菜品
    </div>
    <div>
      <el-select v-model="category" placeholder="请选择分类" @change="getGoodList">
        <el-option
          v-for="item in categoryList"
          :key="item.value"
          :label="item.label"
          :value="item.value">
        </el-option>
      </el-select>
    </div>
    
    <div>
      <el-select v-model="goods" multiple placeholder="请选择商品">
        <el-option
          v-for="item in options"
          :key="item.value"
          :label="item.label"
          :value="item"
          ></el-option>
      </el-select>
    </div>

    <div v-if="goods.length">
      <el-input placeholder="请输入标签名" @change="handleChanged" :value="goods[0].tag"></el-input>
    </div>
    
  </div>
</template>

<script>
import axios from 'axios';

export default {
  props: {
    categoryList: Array,
    currentData: Array
  },
  data() {
    return {
      category: this.currentData[0] ? this.currentData[0].cate : '',
      goods: this.currentData,
      options: []
    };
  },
  watch: {
    goods(value) {
      this.$emit('currentRowChanged', value);
    }
  },
  created() {
    this.getGoodList(this.category, false);
  },
  methods: {
    getGoodList(id, change = true) {
      if (change) this.goods = [];
      if (!id) return;
      const target = this.categoryList.find(item => item.value === id);
      if (target.children) {
        this.options = target.children;
      } else {
        this.fetchGoodList(id);
      }
    },
    fetchGoodList(id) {
      return axios
        .get(`https://nihaocai.zkong.me/api/categories/${id}`)
        .then(res => res.data.data.goods.map(item => this.genGood(item)))
        .then(goodList => {
          this.options = goodList;
          this.$emit('assertGoodList', id, goodList);
        });
    },
    genGood({ id, name, image, sale_price, unit, attributes_by_status }) {
      return {
        value: id,
        good: id,
        label: name,
        image: `${image}?x-oss-process=image/resize,m_pad,h_200,w_200`,
        price: sale_price,
        unit,
        cate: this.category,
        tag: ''
      };
    },
    handleChanged(value) {
      this.goods.forEach(item => (item.tag = value));
    }
  }
};
</script>
